# -*- coding: utf-8 *-*
from DAL import DataAccessLayer
import urllib
import urllib2
import simplejson as json
from google.appengine.api import urlfetch


class BusinessLogicLayer():

    _DAL = None

    def __init__(self):
        self._DAL = DataAccessLayer()

###method that checks if the user id is known in the database
###if the user is not known in the datastore it will request this

    def fetch_access_token(self, fb_api_id, fb_api_url, fb_secret, code):
        result = self._DAL.fetch_access_token(fb_api_id,
                                                                    fb_api_url,
                                                                    fb_secret,
                                                                    code)
        return result

    def fetch_user_full_name(self, fb_api_id, fb_api_url, fb_secret, code):
        acces_token = self._DAL.fetch_access_token(fb_api_id,
                                                                    fb_api_url,
                                                                    fb_secret,
                                                                    code)
        result = self._DAL.fetch_facebook_user_data(acces_token)
        return result
#        access_url = "https://graph.facebook.com/oauth/access_token?"
#        data = urllib.urlencode({'client_id': fb_api_id,
#                                        'redirect_uri': fb_api_url,
#                                        'client_secret': fb_secret,
#                                        'code': code})
#        result = urlfetch.fetch(url=access_url,
#                                        payload=data,
#                                        method=urlfetch.POST,
#headers={'Content-Type': 'application/x-www-form-urlencoded'})
#        access_token = {}
#        answer_data = urllib.unquote(result)
#        split_data = answer_data.split('&')
#        for parts in split_data:
#            part = parts.split('=')
#            access_token[part[0]] = part[1]
#        token = access_token['access_token']
#        graph_url = 'https://graph.facebook.com/me?access_token=%s' % (token)
#        test = urllib2.urlopen(graph_url)
#        data = json.load(test)
#        return result
#        FbU = FbUser(id=int(data['id']), fullname=data['name'])
#        output = FbU.put()

    def fetch_fb_user_id(self, request, fb_secret):
        signed_request_data = request.get("signed_request")
        drd = self._DAL.parse_signed_request(signed_request_data, fb_secret)
        return drd['user_id']
